package com.uit.ecommerce.servlets;

import com.uit.ecommerce.utils.Utils;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author ngloc_it
 */
@WebServlet(name="Login", urlPatterns={"/Login"})
public class Login extends HttpServlet {
  
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("AAAAAAAAAAAAa");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        HttpSession session = req.getSession();

        PrintWriter out = resp.getWriter();
        

        String user = (String)req.getParameter("txtusername");
        String pass = (String)req.getParameter("txtpassword");

        String path = "./jsps/TrangChu.jsp";
        if(!Login(user, pass)){        
            path = "./jsps/DangNhap.jsp";
        }

        session.setAttribute("username", user);
        resp.sendRedirect(path);
    }

    private boolean Login(String userName, String password){
        for(int i = 0; i < Utils.NUM_USER; i++){
            if(Utils.users[i].equals(userName) &&
                    Utils.passwords[i].equals(password))
                return true;
        }
        return false;
    }
}
